package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

const old_str string = "uranus"
const new_str string = "zone"

func main() {

	var f string = os.Args[1]
	fmt.Println("start to replace uranus .....", f)
	if f == "" {
		log.Fatalf("请输入文件目录名字")
		return
	}
	_, err := os.Stat(f)
	if err != nil && os.IsNotExist(err) {
		log.Fatalf("文件或者目录不存在...", f)
		return
	}

	string_stack := []string{}

	string_stack = append(string_stack, f)

	fmt.Println("current string_stack len : ", len(string_stack))

	for len(string_stack) != 0 {

		temp_f := string_stack[len(string_stack)-1]
		string_stack = string_stack[:len(string_stack)-1]
		s1, _ := os.Stat(temp_f)

		fmt.Println("current file : ", temp_f)

		if s1.IsDir() {
			f_new := strings.ReplaceAll(temp_f, old_str, new_str)
			os.Rename(temp_f, f_new)
			//遍历目录，把目录下的所有文件都入栈
			rd, _ := ioutil.ReadDir(f_new)
			for _, fi := range rd {
				string_stack = append(string_stack, f_new+"/"+fi.Name())
			}
		} else {
			replaceFile(temp_f)
		}

	}
}

func replaceFile(f string) {
	if f[0:1] == "." {
		fmt.Println(".开头的文件 忽略:", f)
		return
	}
	bs, err := ioutil.ReadFile(f)
	if err != nil {
		panic(err)
	}
	msg := string(bs)
	msg2 := strings.ReplaceAll(msg, old_str, new_str)

	f_new := strings.ReplaceAll(f, old_str, new_str)
	os.Rename(f, f_new)

	ioutil.WriteFile(f_new, []byte(msg2), 0600)
}

func replaceDir(f string) {

}
